<template>
    <div class="mb-2">
        <div class="my-1 w-80 flex items-center">
            <span class="text-nowrap">本期期号：</span>
            {{ activeDrawInfo.lotteryDrawNum }}
            <span class="text-nowrap ms-2">本期开奖：</span>
            <el-input size="small" v-model="activeDrawInfo.lotteryDrawResult" clearable></el-input>
        </div>
        <div class="my-1 w-80 flex items-center">
            <span class="text-nowrap">上期期号：</span>
            {{ prevDrawInfo.lotteryDrawNum }}
            <span class="text-nowrap ms-2">上期开奖：</span>
            <el-input size="small" v-model="prevDrawInfo.lotteryDrawResult" clearable></el-input>
        </div>
        <div class="my-1 w-120 flex items-center">
            <span class="text-nowrap">模拟开奖：</span>
            <el-select v-model="testLotteryDrawNum" placeholder="请选择" size="small" style="width: 240px"
                @change="onChangeDrawNum">
                <el-option v-for="(item, idx) in dataset" :key="idx"
                    :label="`${item.lotteryDrawNum} - [${item.lotteryDrawResult}]`" :value="item.lotteryDrawNum" />
            </el-select>
            <el-button-group size="small" class="ms-1">
                <el-button type="info" @click="onDrawTesting()">立即开奖</el-button>
                <el-button type="info" @click="onResetTesting()">重置</el-button>
            </el-button-group>
        </div>
        <div class="mb-1">说明：【初选/7列选号池/过滤2】、【初选/前后区选号池/过滤3】、【优选/7列选号池/过滤2】、【优选/前后区选号池/过滤3】中奖率最佳。</div>
        <el-button-group size="small">
            <el-button type="primary" @click="addCard()">添加</el-button>
            <el-button type="warning" @click="batchGenerateOrders()">批量生成号码</el-button>
            <el-button type="warning" @click="batchGenerateOrdersx100()">批量x100并统计</el-button>
            <el-button type="danger" @click="onSave()">保存数据</el-button>
        </el-button-group>
    </div>
    <div class="grid grid-cols-3 gap-4">
        <el-card v-for="(orderItem, orderIdx) of orderList" :key="orderIdx">
            <div>
                <div class="flex items-center">
                    <span class="text-nowrap">选号模式：</span>
                    <el-radio-group v-model="orderItem.param.chooseMode">
                        <el-radio value="初选">初选</el-radio>
                        <el-radio value="优选">优选</el-radio>
                    </el-radio-group>
                </div>
                <div class="flex items-center">
                    <span class="text-nowrap">选号池类型：</span>
                    <el-select size="small" v-model="orderItem.param.poolType" placeholder="请选择" style="width: 240px">
                        <el-option label="前区和后区号码池" value="frontAndBack"></el-option>
                        <el-option label="7列号码池" value="columns"></el-option>
                        <el-option label="7列号码池-前半前半" value="xcolumns-h1h1"></el-option>
                        <el-option label="7列号码池-前半后半" value="xcolumns-h1h2"></el-option>
                        <el-option label="7列号码池-后半前半" value="xcolumns-h2h1"></el-option>
                        <el-option label="7列号码池-后半后半" value="xcolumns-h2h2"></el-option>
                    </el-select>
                </div>
                <div class="flex items-center">
                    <span class="text-nowrap">选号池过滤：</span>
                    <el-select size="small" v-model="orderItem.param.filterLevel" placeholder="请选择" style="width: 240px">
                        <el-option label="全部开奖号码" value="all"></el-option>
                        <el-option label="开奖次数大于 1 次" value="1"></el-option>
                        <el-option label="开奖次数大于 2 次" value="2"></el-option>
                        <el-option label="开奖次数大于 3 次" value="3"></el-option>
                    </el-select>
                </div>
                <div class="flex items-center my-1">
                    <span class="text-nowrap">备注：</span>
                    <el-input size="small" v-model="orderItem.remark" placeholder=""></el-input>
                </div>

            </div>
            <div class="w-120">
                <div v-if="orderItem.list?.length > 0">
                    <div class="flex items-center pb-2 mb-3 border-b-1 border-b-solid border-gray-200">
                        <div class="w-5 text-end pr-2">#</div>
                        <div class="w-40">号码</div>
                        <div class="w-10 ml-2">和值</div>
                        <div class="w-20">操作</div>
                        <div class="w-20">开奖结果</div>
                    </div>
                    <div class="h-83 overflow-y-auto">
                        <div class="flex items-center mt-1" v-for="(item, idx) of orderItem.list" :key="idx">
                            <div class="w-5 text-end pr-2">{{ idx + 1 }}</div>
                            <div class="w-40"><el-input size="small" clearable v-model="orderItem.list[idx]" /></div>
                            <div class="w-10 ml-2">
                                {{orderItem.list[idx].split(' ').reduce((a, b) => parseInt(a) + parseInt(b))}}
                            </div>
                            <div class="w-20">
                                <el-button-group size="small">
                                    <el-button type="danger" @click="onDeleteRow(orderIdx, idx)">删除</el-button>
                                </el-button-group>
                            </div>
                            <div class="w-50 ms-2 text-nowrap">
                                <span v-html="orderItem.drawList[idx]?.text" class="me-1"></span>
                                <span
                                    :class="orderItem.drawList[idx]?.status > 0 ? 'text-red-400 font-bold' : 'text-gray-400'">
                                    {{ orderItem.drawList[idx]?.statusText }}
                                    {{ (orderItem.drawList[idx]?.frontCount || 0) + '+' + (orderItem.drawList[idx]?.backCount || 0) }}
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="text-xs text-gray-400 my-2">
                        {{ orderItem.list?.length }} 注
                        {{ orderItem.list?.length * 2 }} 元
                    </div>
                </div>
                <el-empty v-else>请点击【机选】按钮添加号码。</el-empty>
            </div>
            <div class="flex items-center justify-between">
                <el-button-group size="small">
                    <el-button type="danger" @click="orderItem.list = []; orderItem.drawList = [];">清空</el-button>
                    <el-button type="primary" @click="onChooseAuto(orderIdx)">机选 x1</el-button>
                    <el-tooltip content="机选 10 注" placement="top-start">
                        <el-button type="primary" @click="onChooseAuto(orderIdx, 10)">x10</el-button>
                    </el-tooltip>
                    <el-tooltip content="以机选号码作为号码池，混合后再随机组合号码" placement="top-start">
                        <el-button type="primary" @click="onChooseAutoBetter(orderIdx)">优选</el-button>
                    </el-tooltip>
                </el-button-group>
                <el-button-group size="small">
                    <el-button type="info" @click="onCopy(orderIdx)">复制</el-button>
                    <el-button type="danger" @click="orderList.splice(orderIdx, 1)">删除</el-button>
                </el-button-group>
            </div>
        </el-card>
    </div>
    <div class="mt-1">
        <el-button-group size="small">
            <el-button type="warning" @click="batchGenerateOrders()">批量生成号码</el-button>
        </el-button-group>
    </div>
    <el-drawer v-model="drawerInfo.visible" title="批量生成 100 次号码的统计" resizable>
        <div>共 100 注，支出 200 元</div>
        <section v-for="(item, idx) of drawerInfo.list" :key="idx" class="my-2">
            <h4>{{ item.title }}</h4>
            <div>
                中奖 {{ item.winOrderCount }} 注，
                奖金 {{ item.winMoney }} 元
                <details>
                    <summary>详情</summary>
                    <div v-html="item.drawList.join('<br />')"></div>
                </details>
            </div>
        </section>
    </el-drawer>
</template>

<script setup>
import { ElMessage } from 'element-plus';
import { ref } from 'vue';
import DltDataModel from '@/model/DltDataModel';
import DltOrderModel from '@/model/DltOrderModel';
import DltTplModel from '@/model/DltTplModel';
import FsDriver from '@/model/FsDriver';
import { copyText } from '@/utils/Utils';

const fsDriver = new FsDriver();
const dltTplModel = new DltTplModel();
const dltDataModel = new DltDataModel();
const dltOrderModel = new DltOrderModel();
const dataset = [...dltDataModel.getDataSource()];
const prevDrawInfo = ref(dataset.length > 0 ? dataset[0] : { lotteryDrawNum: '', lotteryDrawResult: '' });
const activeDrawInfo = ref({ lotteryDrawNum: parseInt(prevDrawInfo.value.lotteryDrawNum) + 1 });
const testLotteryDrawNum = ref('');
const orderList = ref([]);
const drawerInfo = ref({ visible: false, list: [] })

const onChangeDrawNum = (e) => {
    for (let i in dataset) {
        if (dataset[i].lotteryDrawNum == e) {
            activeDrawInfo.value = dataset[i];
            prevDrawInfo.value = dataset[parseInt(i) + 1] || { lotteryDrawNum: '', lotteryDrawResult: '' };
            console.log(i, e, dataset[i].lotteryDrawNum);
            break;
        }
    }
}

const onResetTesting = () => {
    prevDrawInfo.value = dataset.length > 0 ? dataset[0] : {};
    activeDrawInfo.value = { lotteryDrawNum: parseInt(prevDrawInfo.value?.lotteryDrawNum) + 1 };
}

const onDrawTesting = () => {
    if (!activeDrawInfo.value.lotteryDrawResult) {
        ElMessage.error('请输入本期开奖结果');
        return;
    }
    orderList.value.forEach(orderItem => {
        orderItem.drawList = dltOrderModel.calcOrder(activeDrawInfo.value.lotteryDrawResult, orderItem.list, false, prevDrawInfo.value.lotteryDrawResult);
    })
}
const addCard = () => {
    orderList.value.push({ ...dltTplModel.getTplForOrderListItem() });
}

const batchGenerateOrders = () => {
    orderList.value = [];
    let batchParamList = dltTplModel.getAllTplParams();
    batchParamList.forEach(param => {
        orderList.value.push({ ...dltTplModel.getTplForOrderListItem({ param }) });
    });
    let n = orderList.value.length,
        drawResult = activeDrawInfo.value?.lotteryDrawResult?.trim(),
        prevDrawResult = prevDrawInfo.value?.lotteryDrawResult?.trim();
    let isDraw = drawResult?.length > 0;
    for (let orderIdx = 0; orderIdx < n; orderIdx++) {
        orderList.value[orderIdx].list = [];
        orderList.value[orderIdx].drawList = [];
        onChooseAuto(orderIdx, 10);
        if (orderList.value[orderIdx].param.chooseMode == '优选') {
            orderList.value[orderIdx].list = dltOrderModel.getBetterNums7(orderList.value[orderIdx].list)
        }
        if (isDraw) {
            orderList.value[orderIdx].drawList = dltOrderModel.calcOrder(drawResult, orderList.value[orderIdx].list, false, prevDrawResult);
        }
    }
}

const batchGenerateOrdersx100 = () => {
    let drawResult = activeDrawInfo.value?.lotteryDrawResult?.trim();
    let prevDrawResult = prevDrawInfo.value?.lotteryDrawResult?.trim();
    if (!drawResult) {
        ElMessage.error('请选择一期已开奖的开奖结果');
        return;
    }
    drawerInfo.value.visible = true;

    let list = [];
    let batchList = [];
    let batchParamList = dltTplModel.getAllTplParams();
    batchParamList.forEach(param => {
        batchList.push({ ...dltTplModel.getTplForOrderListItem({ param }) });
    });
    let nums = [];
    batchList.forEach(item => {
        item.list = [];
        item.drawList = [];
        for (let i = 0; i < 100; i++) {
            nums = dltOrderModel.getRandomNums7(item.param.poolType, item.param.filterLevel, prevDrawResult);
            item.list.push(nums[0].join(' ') + ' ' + nums[1].join(' '));
        }

        if (item.param.chooseMode == '优选') {
            item.list = dltOrderModel.getBetterNums7(item.list)
        }
        item.drawList = dltOrderModel.calcOrder(drawResult, item.list, true, prevDrawResult);


        list.push({
            title: `${item.param.buildType} / ${dltTplModel.getParamPoolTypeText(item.param.poolType)} / 选号池过滤 ${item.param.filterLevel} / ${item.param.chooseMode}`,
            winOrderCount: item.drawList.length,
            winMoney: item.drawList.length > 0 ? item.drawList.map(v => v.money).reduce((a, b) => parseInt(a) + parseInt(b)) : 0,
            prizeText: item.drawList.map(v => `${v.statusText}(${v.moneyText})`).join(' / '),
            drawList: item.drawList.map(v => `${v.text} ${v.statusText}（${v.moneyText}元）（${v.frontCount}+${v.backCount}=${v.frontCount + v.backCount}）`),
        })
    })
    batchList = null;
    drawerInfo.value.list = list;
}
const onDeleteRow = (orderIdx, idx) => {
    orderList.value[orderIdx].list.splice(idx, 1);
}

const onCopy = (orderIdx) => {
    copyText(orderList.value[orderIdx].list.join('\n'));
    ElMessage.success('复制成功');
}

const onSave = () => {
    if (list.value.length == 0) {
        ElMessage.error('内容不能为空');
        return;
    }
    fsDriver.save('temp-order', JSON.stringify({
        ...dltTplModel.getTplForFileData({
            PrevDrawalInfo: prevDrawInfo.value,
            DrawalInfo: {
                lotteryDrawNum: activeDrawInfo.value.lotteryDrawNum,
                lotteryDrawResult: "",
                lotteryDrawTime: ""
            },
            OrderList: orderList.value
        })
    }));
    ElMessage.success('保存成功');
}
/**
 * 机选一注
 */
const onChooseAuto = (orderIdx, count = 1) => {
    let nums = [], n = count == 1 ? count : (count - orderList.value[orderIdx].list.length);
    let filterLevel = parseInt(orderList.value[orderIdx].param.filterLevel);
    let poolType = orderList.value[orderIdx].param.poolType;
    while (n > 0) {
        nums = dltOrderModel.getRandomNums7(poolType, filterLevel, prevDrawInfo.value.lotteryDrawResult);
        orderList.value[orderIdx].list.push(nums[0].join(' ') + ' ' + nums[1].join(' '));
        n--;
    }
}

/**
 * 优选（在机选号码里面继续机选）
 */
const onChooseAutoBetter = (orderIdx) => {
    if (orderList.value[orderIdx].list.length == 0) {
        ElMessage.error('请先选择机选的号码');
        return;
    }
    orderList.value[orderIdx].list = dltOrderModel.getBetterNums7(orderList.value[orderIdx].list);
}
const fetchData = () => {

}

</script>